package org.anti996.bankms.controller;

import org.anti996.bankms.dao.UserDao;
import org.anti996.bankms.model.Account;
import org.anti996.bankms.model.Card;
import org.anti996.bankms.util.IOUtil;
import org.anti996.bankms.util.MessageUtil;
import org.anti996.bankms.view.UserView;

import java.util.List;

public class UserController extends ControllerBase {
    private Account account_ = null;
    private List<Card> cards_ = null;
    private int retryTimes_ = 4;

    public UserController() {
        super(new UserView());
    }

    private void login() {
        MessageUtil.info("请输入用户名：");
        String username = IOUtil.parseInput();
        MessageUtil.info("请输入密码：");
        String password = IOUtil.parsePassword();
        account_ = UserDao.login(username, password);
        if (account_ != null) {
            cards_ = UserDao.getAllCards(account_);
            MessageUtil.success("登录成功");
        }
    }

    @Override
    public void deal() {
        if (account_ == null) {
            if (0 < retryTimes_ && retryTimes_ < 4) {
                MessageUtil.warning("用户名或密码错误，请重新输入，还可尝试" + retryTimes_ + "次");
            } else if (retryTimes_ == 0) {
                MessageUtil.error("用户名或密码错误，登录失败");
                Navigator.pop();
                return;
            } else if (retryTimes_ == 4) {
                MessageUtil.title("用户登录");
            }
            login();
            --retryTimes_;
        } else {
            super.deal();
            int order = IOUtil.parseOrder();
            switch (order) {
                case 1 -> {
                    MessageUtil.title("用户信息");
                    MessageUtil.infoln(Account.describe(account_));
                    waitForKeyPress();
                }
                case 2 -> Navigator.push(new UserInfoUpdateController(account_));
                case 3 -> Navigator.push(new UserCardController(cards_));
                case 4 -> Navigator.push(new UserPutMoneyInController(cards_));
                case 5 -> Navigator.push(new UserPutMoneyOutController(cards_));
                case 6 -> Navigator.push(new UserTransferMoneyController(cards_));
                case 7 -> Navigator.pop();
                default -> wrongInputAndRetry();
            }
        }
    }
}
